// Copyright (c) 2025 coze-dev Authors
// SPDX-License-Identifier: Apache-2.0
import { join } from 'node:path';
import { writeFile } from 'node:fs/promises';

import { localeEnUS, localeZhCN } from '@cozeloop/loop-lng';

import { icu2Type } from './utils';

function generateOptionsMap(locales: Record<string, string>, indent: string) {
  const functionTypes: string[] = [];
  const indent2 = indent + indent;
  const indent3 = indent2 + indent;
  for (const [key, content] of Object.entries(locales)) {
    const typeInfos = icu2Type(content);
    const lines = [`${indent}/** ${localeZhCN[key]} */`];

    if (!typeInfos.length) {
      lines.push(`${indent}(key: '${key}', fallbackText?: string): string;`);
    } else {
      lines.push(`${indent}(`);
      lines.push(`${indent2}key: '${key}',`);
      lines.push(`${indent2}options?: {`);
      for (const typeInfo of typeInfos) {
        lines.push(
          `${indent3}/** ${typeInfo.type} */ ${typeInfo.key}: ReactNode;`,
        );
      }
      lines.push(`${indent2}},`);
      lines.push(`${indent2}fallbackText?: string,`);
      lines.push(`${indent}): string;`);
    }
    functionTypes.push(lines.join('\n'));
  }

  return functionTypes;
}

async function main() {
  const startAt = Date.now();
  const functionTypes = generateOptionsMap(localeEnUS, '  ');
  const localeTypes = `// Copyright (c) 2025 coze-dev Authors
// SPDX-License-Identifier: Apache-2.0
/* eslint-disable
  max-lines,
  prettier/prettier,
  @typescript-eslint/naming-convention,
  @typescript-eslint/unified-signatures
-- skip */
/** Generated by rushx gen-i18n-types */
import { type ReactNode } from 'react';

import { type intlClient } from '@cozeloop/intl';

interface I18nTranslateFn {
${functionTypes.join('\n')}
}

/** I18n of Cozeloop */
export type CozeloopI18n = Omit<typeof intlClient, 't'> & {
  t: I18nTranslateFn;
};
`;

  const typeFile = join(__dirname, '..', 'src/locale-types.ts');
  await writeFile(typeFile, localeTypes);
  console.info(`🕙 Time cost: ${Date.now() - startAt}ms`);
  console.info(`✅ Locale types generated in ${typeFile}`);
}

main();
